package com.example.newone.service.impl;

import com.example.newone.dao.UserDao;
import com.example.newone.mappper.UserMapper;
import com.example.newone.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<UserDao> findUser() {
        List<UserDao> user = userMapper.findUser();
        return user;
    }

    @Override
    public List<UserDao> findTree() {
        List<UserDao> user = userMapper.findUser();

        return createTree(user);
    }

    @Override
    public void insert(UserDao userDao) {
    userDao.setCreateTime(new Date());
    if ("null".equals(userDao.getParentId())){
        userDao.setParentId(0);
    }
    userMapper.insertUser(userDao);
    }

    @Override
    public void deleteUser(Long id) {
        userMapper.deleteUser(id);
    }

    @Override
    public void updateUser(UserDao userDao) {

        userMapper.updateUser(userDao);
    }

    public List<UserDao> createTree(List<UserDao> list){
        List<UserDao> tree = new ArrayList<>();
        for (UserDao userDao : list) {
            if (0 == userDao.getParentId()){
                tree.add(findChildren(userDao,list));
            }
        }
        return tree;
    }

    private UserDao findChildren(UserDao userDao, List<UserDao> list) {
        for (UserDao dao : list) {
            if (userDao.getId()==dao.getParentId()){
                if (userDao.getChildren()==null){
                    userDao.setChildren(new ArrayList<>());
                }
                userDao.getChildren().add(findChildren(dao,list));
            }
        }
        return userDao;
    }


}
